package com.wcj.linktable;

import java.util.List;

/**
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 '
 * 输入：l1 = [1,2,4], l2 = [1,3,4]
 * 输出：[1,1,2,3,4,4]
 */
public class 合并两个有序链表 {

    public static void main(String[] args) {
        ListNode list1 = new ListNode(1);
        list1.next = new ListNode(2);
        list1.next.next = new ListNode(4);
        ListNode list2 = new ListNode(1);
        list2.next = new ListNode(3);
        list2.next.next = new ListNode(4);
        mergeTwoLists(list1,list2);
    }


    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null){
            return list2;
        }
        if (list2 == null){
            return list1;
        }
        ListNode point1 = list1;
        ListNode point2 = list2;
        ListNode point2Pre = null;
        while (point1 != null && point2 != null){
            ListNode tmp = point1.next;
            if (point1.val <= point2.val){

                if (point2Pre == null){
                    point1.next = point2;
                    list2 = point1;
                    point2Pre = point1;
                    point1 = tmp;
                }else {
                    point2Pre.next = point1;
                    point1.next = point2;
                    point2Pre = point1;
                    point1 = tmp;
                }

            }else if (point1.val > point2.val && (point2.next==null || point2.next.val >= point1.val)){
                point1.next = point2.next;
                point2.next = point1;
                point1 = tmp;
            }else {
                point2Pre = point2;
                point2 = point2.next;
            }

        }
        return list2;
    }
}
